package com.dxy.lc.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.dxy.lc.base.AppConstant;
import com.dxy.lc.base.Resp;
import com.dxy.lc.socketio.ISession;
import com.dxy.lc.socketio.ISessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/lc/test")
@ConditionalOnProperty(value = "test.controller.enable", havingValue = "true")
public class TestController {

    @Autowired
    private ISessionService sessionService;

    @PostMapping("/testSendMessageByUserId")
    public Resp testSendMessageByUserId(@RequestParam String userId,
                                        @RequestParam String event,
                                        @RequestBody JSONObject message){
        log.info("testSendMessageByUserId, userId: {}, event: {}, message: {}", userId, event, message);
        sessionService.sendMessageByUserId(userId, event, message);
        return Resp.bizSuccess();
    }

    @PostMapping("/testSendMessageByRoomId")
    public Resp testSendMessageByRoomId(@RequestParam String roomId,
                                        @RequestParam String event,
                                        @RequestBody JSONObject message){
        log.info("testSendMessageByRoomId, roomId: {}, event: {}, message: {}", roomId, event, message);
        sessionService.sendMessageByRoomId(roomId, event, message);
        return Resp.bizSuccess();
    }

    @GetMapping("/testCloseSocketSession")
    public Resp testCloseSocketSession(String userId){
        Assert.notBlank(userId);
        Set<String> sessionIds = sessionService.getUserBind(userId);
        if (CollUtil.isNotEmpty(sessionIds)){
            sessionIds.forEach(sessionId -> {
                ISession session = sessionService.getSessionById(sessionId);
                String token = session.getConnectParam(AppConstant.QUERY_TOKEN_KEY);
                log.info("测试服务端退出..., token: {}", token);
                session.sendMessage(AppConstant.SOCKET_EVENT_SERVER_LOGOUT, "token expired");
                session.close();
            });
        }
        return Resp.bizSuccess();
    }
}
